import React, { Component } from 'react';
import { base, getMultiLang, createPage, cardCache, toast, promptBox, viewModel, pageTo } from 'nc-lightapp-front';
import Inspection from 'epmp/exports/components/Inspection';
import config from './config';
import api from '../../common/api';
import _ from 'lodash-es'
import QuickShare from '../../../../expenseaccount/expenseaccount/card/components/QuickShare';
import {
    onPageButtonClick,
    onSearchButtonClick,
    onBackButtonClick,
    onTableButtonClick,
    onTableAfterEvent,
    onTableBeforeEvent
} from './events';

const { setDefData, getDefData } = cardCache;
const { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;
const { NCModal, NCAffix, NCPopconfirm, NCFormControl, NCAnchor, NCScrollElement, NCScrollLink, NCDiv } = base;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.form(config.headcode);
        props.use.cardTable(config.bodycode);
        this.state = {
            multilang: {},
            isInspectionShowed: false,
            inspectionSourceData: {},
            showQuickShare: false
        };

        const searchParams = new URLSearchParams(window.location.hash.substring(window.location.hash.indexOf('?')));
        if (searchParams.get('bxdpk')) {
            props.setUrlParam({
                bxdpk: searchParams.get('bxdpk'),
                status: 'add'
            });
        } else if (searchParams.get('id')) {
            props.setUrlParam({
                id: searchParams.get('id')
            });
        } else {
            props.setUrlParam({
                status: 'browse'
            });
        }
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multilang,
            callback: json => {
                this.setState({ multilang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, data => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template);
                    });
                });
            }
        });
    }

    setMeta(meta) {
        let PublicDefaultRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder';//公共 
        const props = this.props;
        // const { setPageStatus } = this.props;
        meta[config.headcode].status = props.getUrlParam('status');
        
        meta[config.headcode].items.forEach(item => {
            if(item.attrcode === 'zy') {
                item.queryCondition = () => {

                    return {
                        crossrule_tradetype: props.form.getAllFormValue('head').rows[0].values['pk_tradetype'].value,
                        pk_org: props.form.getAllFormValue('head').rows[0].values['pk_org'].value,
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                }
            }
            else if(item.attrcode=='fydeptid'){
                //费用承担部门
                // item.refcode='uapbd/refer/org/DeptTreeRef/index'
                item.queryCondition = ()=>{
                    //let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
                    let data = props.form.getAllFormValue('head').rows[0].values['fydwbm'].value
                    return {pk_org: data,TreeRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef',DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
                }
            }
            // NEXT1 性能优化，互斥判断修改为else if chengwbc MOD
            else if(item.attrcode=='fydeptid_v'){
                //费用承担部门版本
                // item.refcode='uapbd/refer/org/DeptTreeRef/index'
                item.queryCondition = ()=>{
                    //let data = dataValues['fydwbm']==null?"":dataValues['fydwbm'].value;
                    let data = props.form.getAllFormValue('head').rows[0].values['fydwbm'].value
                    return {pk_org: data,DataPowerOperationCode:'fi',/**使用权组**/isDataPowerEnable:'Y'}; // 根据apply_org过滤
                }
            }
            else if(item.attrcode == 'bx_pcorg') {
                // 利润中心
                item.queryCondition = () => {
                    let crossrule_org = props.form.getAllFormValue('head').rows[0].values['fydwbm'].value
                    return {
                        crossrule_org: crossrule_org,
                        pk_org: crossrule_org,
                        TreeRefActionExt: '',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
            else if(item.attrcode == 'pk_resacostcenter'){
                let bodys = Object.values(config.bodycode);
                let bodyarr = [];
                bodys.forEach((one)=>{
                        bodyarr[bodyarr.length] = one;
                })
                //成本中心
                item.queryCondition = ()=>{
                    let pk_pcorg = props.form.getAllFormValue('head').rows[0].values['bx_pcorg'].value
                    let pk_group = props.form.getAllFormValue('head').rows[0].values['pk_group'].value
                    let pk_org = props.form.getAllFormValue('head').rows[0].values['fydwbm'].value
                    let crossrule_datasout = props.createExtCardData(pageTo.getSearchParam("p"), "head", bodyarr);
                    let crossrule_tradetype = props.form.getFormItemsValue(config.headcode,'djlxbm').value;
                    let crossrule_org =  props.form.getFormItemsValue(config.headcode,'pk_org').value;
                    let crossrule_datas = crossrule_datasout;
                    let crossrule_datatypes = 'extbillcard';
                    let crossrule_itemkey = item.attrcode;
                    let isHead = "true"
                    return {
                        crossrule_datas:JSON.stringify(crossrule_datas),
                        crossrule_tradetype:crossrule_tradetype,
                        crossrule_org:crossrule_org, 
                        crossrule_datatypes:crossrule_datatypes,
                        crossrule_area:config.headcode,
                        crossrule_itemkey:crossrule_itemkey,
                        crossrule_isHead : isHead,
                        pk_org: pk_org,
                        pk_group: pk_group,
                        pk_profitcenter: pk_pcorg,
                        TreeRefActionExt:PublicDefaultRefFilterPath,
                        DataPowerOperationCode:'fi',/**使用权组**/
                        isDataPowerEnable:'Y'
                    };
                }    
            }
        })        

        meta[config.bodycode].items.forEach((item) => {
            if (!item.visible) return;
            if (item.itemtype === 'refer' && item.attrcode == 'assume_dept') {
                item.queryCondition = () => {
                    return {
                        pk_org: getDefData('pk_org', config.datasource),
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            } 
            else if(item.itemtype === 'refer' && item.attrcode == 'pk_pcorg') {
                // 利润中心
                item.queryCondition = () => {
                    let crossrule_org = getDefData('pk_org', config.datasource)
                    return {
                        crossrule_org: crossrule_org,
                        pk_org: getDefData('pk_org', config.datasource),
                        TreeRefActionExt: '',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }

            
            else if(item.itemtype === 'refer' && item.attrcode == 'pk_resacostcenter'){
                let bodys = Object.values(config.bodycode);
                let bodyarr = [];
                bodys.forEach((one)=>{
                        bodyarr[bodyarr.length] = one;
                })
                //成本中心
                item.queryCondition = ()=>{
                    let crossrule_datasout = props.createExtCardData(pageTo.getSearchParam("p"), "head", bodyarr);
                    let pk_pcorg = props.cardTable.getClickRowIndex(config.bodycode).record.values['pk_pcorg'].value
                    let crossrule_tradetype = props.form.getFormItemsValue(config.headcode,'djlxbm').value;
                    let crossrule_org =  props.form.getFormItemsValue(config.headcode,'pk_org').value;
                    let crossrule_datas = crossrule_datasout;
                    let pk_group = props.form.getAllFormValue(config.headcode).rows[0].values['pk_group'].value
                    let pk_org = props.cardTable.getClickRowIndex(config.bodycode).record.values['assume_org'].value
                    let crossrule_datatypes = 'extbillcard';
                    let crossrule_itemkey = item.attrcode;
                    let isHead = "false"
                    return {
                        crossrule_datas:JSON.stringify(crossrule_datas),
                        crossrule_tradetype:crossrule_tradetype,
                        crossrule_org:crossrule_org, 
                        crossrule_datatypes:crossrule_datatypes,
                        crossrule_area:config.bodycode,
                        crossrule_itemkey:crossrule_itemkey,
                        crossrule_isHead : isHead,
                        pk_org: pk_org,
                        pk_group: pk_group,
                        pk_profitcenter: pk_pcorg,
                        TreeRefActionExt:PublicDefaultRefFilterPath,
                        DataPowerOperationCode:'fi',/**使用权组**/
                        isDataPowerEnable:'Y'
                    };
                }    
            }
        });

        meta[config.bodycode].items.push({
            label: this.state.multilang['opr_title'],
            itemtype: 'customer',
            attrcode: 'opr',
            width: '100px',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                const status = props.getUrlParam('status');
                if (status === 'edit' || status === 'add') {
                    return props.button.createOprationButton(['table_delete'], {
                        area: config.innerButtonArea,
                        buttonLimit: 3,
                        onButtonClick: (props, key) => onTableButtonClick.call(this, props, key, text, record, index)
                    });
                }
                return null;
            }
        });

        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);
        // props.button.setPopContent(['delete', 'cancel'], '确认要执行该操作吗？');
    }

    initPage() {
        const props = this.props;
        // if (!getDefData('pk_org', config.datasourceCommon)) {
        //     api.getUserInfo().then((data) => {
        //         setDefData('pk_org', config.datasourceCommon, data.pk_org);
        //     });
        // }
        this.setPageStatus(props.getUrlParam('status'));
        this.loadData();
    }

    setPageStatus(status = 'browse') {
        const props = this.props;
        props.setUrlParam({ status });
        if (status === 'add') {
            props.form.setFormStatus(config.headcode, 'add');
            props.cardTable.setStatus(config.bodycode, 'add');
            props.button.setButtonDisabled(['edit', 'delete'], true);
            props.button.setButtonDisabled(['temp_save', 'save', 'cancel', 'quickShare'], false);
        } else if (status === 'edit') {
            props.form.setFormStatus(config.headcode, 'edit');
            props.cardTable.setStatus(config.bodycode, 'edit');
            props.button.setButtonDisabled(['edit', 'delete'], true);
            props.button.setButtonDisabled(['temp_save', 'save', 'cancel', 'quickShare'], false);
        } else {
            props.form.setFormStatus(config.headcode, 'browse');
            props.cardTable.setStatus(config.bodycode, 'browse');
            props.button.setButtonDisabled(['edit', 'delete'], false);
            props.button.setButtonDisabled(['temp_save', 'save', 'cancel', 'quickShare'], true);
        }
    }

    loadData() {
        const props = this.props;
        const status = props.getUrlParam('status');
        let promise;
        if (status === 'add') {
            const bxdpk = props.getUrlParam('bxdpk');
            if (!bxdpk) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['bad_request']
                });
                return;
            }
            const params = {
                pkBx: bxdpk,
                appcode: config.appcode,
                pagecode: config.pagecode
            };
            promise = api.getDetailByReimbursement(params);
        } else {
            const id = props.getUrlParam('id');
            if (!id) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['bad_request']
                });
                return;
            }
            const params = {
                pks: id,
                appcode: config.appcode,
                pagecode: config.pagecode
            };
            promise = api.getDetailByPk(params);
        }

        promise.then(data => {
            // TODO 数据验证
            toast({
                color: 'success',
                content: this.state.multilang['query_success']
            });
            this.setData(data);
            // 报销单id
            // data.head[config.headcode].rows[0].values.src_id.value
        });
    }

    setData(data) {
        const props = this.props;
        props.form.setAllFormValue({ [config.headcode]: data.head[config.headcode] });
        if (data.body && data.body[config.bodycode]) {
            props.cardTable.setTableData(config.bodycode, data.body[config.bodycode]);
        } else {
            props.cardTable.setTableData(config.bodycode, { rows: [] });
        }
        if (!props.getUrlParam('id')) {
            props.setUrlParam({
                id: _.get(data, `head.${config.headcode}.rows[0].values.pk_costshare.value`, '')
            });
        }
        this.setBillStatus();
    }

    // 审核状态
    // public static final int DJZT_TempSaved = 0;  //单据状态——暂存
    // public static final int DJZT_Saved = 1; //单据状态——保存
    // public static final int DJZT_Verified = 2;//单据状态——审核
    // public static final int DJZT_Sign = 3; //单据状态——签字
    // public static final int DJZT_Invalid = -1; //单据状态——作废
    setBillStatus() {
        const props = this.props;
        const billstatus = props.form.getFormItemsValue(config.headcode, 'billstatus');
        const srcType = props.form.getFormItemsValue(config.headcode, 'src_type');
        if (srcType.value === '0') {
            if (billstatus.value === '0') {
                props.button.setButtonDisabled(['approve_group'], true);
            } else if (billstatus.value === '1') {
                props.button.setButtonDisabled(['unapprove'], true);
                props.button.setButtonDisabled(['approve_group', 'approve'], false);
                props.button.setButtonVisible(['temp_save'], false);
            } else if (billstatus.value === '3') {
                props.button.setButtonDisabled(['edit', 'delete', 'approve'], true);
                props.button.setButtonDisabled(['approve_group', 'unapprove'], false);
            }
        } else {
            props.button.setButtonDisabled(['edit', 'delete', 'temp_save', 'save', 'cancel', 'approve_group'], true);
        }
    }

    checkValid() {
        const props = this.props;
        if (!props.form.isCheckNow(config.headcode)) {
            return;
        }
        if (!props.cardTable.checkTableRequired(config.bodycode)) {
            return;
        }
        const rows = props.cardTable.getVisibleRows(config.bodycode);
        const total = Number(props.form.getFormItemsValue(config.headcode, 'total').value);
        const input = rows.map(a => a.values.assume_amount.value).reduce((acc, cur) => Number(acc) + Number(cur), 0);
        if (total !== input) {
            toast({ color: 'warning', title: '报销金额不一致' }); /* 国际化处理： 请选择数据操作！*/
            return;
        }
        return true;
    }

    save() {
        const props = this.props;
        if (!this.checkValid()) return;

        const reqData = props.createMasterChildData(config.pagecode, config.headcode, config.bodycode);
        api.saveCostShare(reqData).then(data => {
            toast({
                color: 'success',
                content: '保存成功'
            }); /* 国际化处理： 查询成功，共,条*/
            this.setPageStatus('browse');
            this.setData(data);
        });
    }
    saveTemporarily() {
        const props = this.props;
        if (!this.checkValid()) return;

        const reqData = props.createMasterChildData(config.pagecode, config.headcode, config.bodycode);
        api.saveCostShareTemporarily(reqData).then(data => {
            toast({
                color: 'success',
                content: '暂存成功'
            }); /* 国际化处理： 查询成功，共,条*/
            this.setPageStatus('browse');
            this.setData(data);
        });
    }

    delete(record) {
        const props = this.props;
        promptBox({
            color: 'warning',
            title: this.state.multilang['delete'] /* 国际化处理： 删除*/,
            content: this.state.multilang['confirm_delete_select'] /* 国际化处理： ​​确定要删除所选数据吗？*/,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: this.state.multilang['confirm'] /* 国际化处理： 确定*/,
            cancelBtnName: this.state.multilang['cancel'] /* 国际化处理： 取消*/,
            beSureBtnClick: () => {
                const pk = props.form.getFormItemsValue(config.headcode, 'pk_costshare');
                api.deleteCostShare({ pks: pk.value || '' }).then(data => {
                    toast({
                        color: 'success',
                        content: this.state.multilang['operate_success']
                    });
                    props.pushTo('/', {
                        status: 'browse',
                        pagecode: config.pagecode
                    });
                });
            }
        });
    }

    approve(record) {
        const props = this.props;
        const pk = props.form.getFormItemsValue(config.headcode, 'pk_costshare');

        api.approveCostShare({ pks: pk.value || '', pagecode: config.pagecode, from: 'card' }).then(data => {
            toast({
                color: 'success',
                content: this.state.multilang['operate_success']
            });
            this.setData(data);
        });
    }

    cancelApprove(record) {
        const props = this.props;
        const pk = props.form.getFormItemsValue(config.headcode, 'pk_costshare');
        api.cancelApprovalCostShare({ pks: pk.value || '', pagecode: config.pagecode, from: 'card' }).then(data => {
            toast({
                color: 'success',
                content: this.state.multilang['operate_success']
            });
            this.setData(data);
        });
    }

    renderTableHead() {
        const props = this.props;
        const status = props.getUrlParam('status');
        if (status !== 'edit' && status !== 'add') {
            return null;
        }
        return (
            <div className="shoulder-definition-area">
                <div className="definition-icons">
                    {this.props.button.createButtonApp({
                        area: config.tableButtonArea, //按钮注册中的按钮区域
                        //buttonLimit: 5,
                        onButtonClick: onTableButtonClick.bind(this)
                    })}
                </div>
            </div>
        );
    }

    renderErrorCenterState() {
        const { props } = this;
        const { socket } = props;
        const status = props.form.getFormItemsValue(config.headcode, 'saga_status');
        if (!status || status.value !== '1') return null;

        this.props.button.toggleErrorStatus(config.pageButtonArea, {
            isError: true
        });

        const param = {
            headBtnAreaCode: config.pageButtonArea,
            formAreaCode: config.headcode,
            billtype: props.form.getFormItemsValue(config.headcode, 'saga_status').value,
            billpkname: config.billpkname,
            dataSource: config.datasource
        };
        return props.socket.connectMesg(param);
    }

    // 快速分摊关闭
    closeQuickShare = () => {
        this.setState({showQuickShare: false});
    }

    getQuickShareParams() {
        const paramdata = {}
        let billdata = this.props.createHeadAfterEventData('20110ETEA_2641_IWEB', "head", [config.bodycode]);
        const pk_org = this.props.form.getFormItemsValue('head', 'pk_org')
        paramdata.pk_org = pk_org
        billdata.card.head.userjson = JSON.stringify(paramdata);
        return { billdata: billdata.card, pk_org }
    }

    getQuickShareAmount() {
        let total = this.props.form.getFormItemsValue('head', 'total');
        const index_obj =  this.props.cardTable.getClickRowIndex(config.bodycode);
        if(index_obj && index_obj.record && index_obj.record.status != '3') {
            total = index_obj.record.values.assume_amount
        }
        return total
    }

    onQuickShareClick(rulePk) {
        // 选择快速分摊规则,开始快速分摊
        if(rulePk) {
            const paramdata = {
                "value":'',
                "tableid":'headform',
                "field":'',
                "uistate": pageTo.getUrlParam('status'),
                "tradetype": pageTo.getUrlParam('tradetype'),
                "oldvalue":'',
                "pagecode": config.pagecode,
                "appcode": config.appcode
            }
            //是否选择继续分摊
            const index_obj =  this.props.cardTable.getClickRowIndex(config.bodycode)
            if(index_obj && index_obj.record && index_obj.record.status != '3') {
                paramdata.changeRowId = index_obj.record.rowid;
                paramdata.tableid = config.bodycode;
            }
            let billdata = this.props.createHeadAfterEventData(config.pagecode, config.headcode, [config.bodycode]);
            const pk_org = this.props.form.getFormItemsValue(config.headcode, 'pk_org');
            paramdata.pk_org = pk_org.value;
            paramdata.shareRulePk = rulePk;
            billdata.card.head.userjson = JSON.stringify(paramdata);
            billdata.templetid = this.props.meta.getMeta().pageid;
            api.quickShare(billdata.card).then((data) => {
                if (data.bodys && data.bodys[config.bodycode]) {
                    this.props.cardTable.setTableData(config.bodycode, data.bodys[config.bodycode]);
                } else {
                    this.props.cardTable.setTableData(config.bodycode, { rows: [] });
                }
            });
        }
    }

    render() {
        const { cardTable, button, form, modal, BillHeadInfo } = this.props;
        // let { cardTable, form, button, modal, cardPagination, transferTable } = this.props;

        return (
            <div className="nc-bill-card">
                {this.renderErrorCenterState()}
                <div className="nc-bill-top-area">
                    <NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
                        <div className="header-title-search-area">
                            {BillHeadInfo.createBillHeadInfo({
                                title: this.state.multilang['card_page_title'],
                                backBtnClick: onBackButtonClick.bind(this)
                            })}
                        </div>
                        <div className="header-button-area">
                            {button.createErrorFlag({
                                headBtnAreaCode: config.pageButtonArea
                            })}
                            {button.createButtonApp({
                                area: config.pageButtonArea,
                                onButtonClick: onPageButtonClick.bind(this)
                            })}
                            {/* {createCardPagination({
                            handlePageInfoChange: this.pageInfoClick.bind(this),
                            dataSource: dataSource
                        })} */}
                        </div>
                    </NCDiv>
                    <div className="nc-bill-form-area">
                        {form.createForm(config.headcode, {
                            onAfterEvent: onTableAfterEvent.bind(this),
                            // onBeforeEvent: formBeforeEvent.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-bill-bottom-area">
                    <div className="nc-bill-table-area">
                        {cardTable.createCardTable(config.bodycode, {
                            tableHead: this.renderTableHead.bind(this),
                            onAfterEvent: onTableAfterEvent.bind(this),
                            onBeforeEvent: onTableBeforeEvent.bind(this)
                        })}
                    </div>
                </div>

                {this.state.isInspectionShowed && (
                    <Inspection
                        show={this.state.isInspectionShowed}
                        sourceData={this.state.inspectionSourceData}
                        cancel={() => this.setState({ isInspectionShowed: false })}
                        affirm={() => this.setState({ isInspectionShowed: true })}
                    />
                )}

                {/* 快速分摊 */}
                <QuickShare size="lg" show={ this.state.showQuickShare } title={ this.state.multilang && this.state.multilang['quick_share_title'] }
                    onHide={ this.closeQuickShare.bind(this) }
                    getQuickShareParams={this.getQuickShareParams.bind(this)} 
                    getQuickShareAmount={this.getQuickShareAmount.bind(this)}
                    onQuickShareClick={this.onQuickShareClick.bind(this)}
                    parentProps={this.props} 
                />
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
